import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as cartAction from '../store/actions/cart.actions'

class Cart extends Component {
  componentDidMount() {
    const { loadCarts } = this.props
    loadCarts()
  }
  changeProductNumber(cid, event) {
    const count = event.target.value
    const { changeProductCount } = this.props
    changeProductCount({cid, count})
  }
  render() {
    const { carts, deleteCarts } = this.props
    return (
      <section className="container content-section">
        <h2 className="section-header">购物车</h2>
        <div className="cart-row">
          <span className="cart-item cart-header cart-column">商品</span>
          <span className="cart-price cart-header cart-column">价格</span>
          <span className="cart-quantity cart-header cart-column">数量</span>
        </div>
        <div className="cart-items">
          {carts.map((product, index) => (
            <div className="cart-row" key={index}>
              <div className="cart-item cart-column">
                <img
                  alt=""
                  className="cart-item-image"
                  src={window.BASE_URL + product.thumbnail}
                  width="100"
                  height="100"
                />
                <span className="cart-item-title">{product.title}</span>
              </div>
              <span className="cart-price cart-column">￥{product.price}</span>
              <div className="cart-quantity cart-column">
                <input
                  className="cart-quantity-input"
                  value={product.count}
                  onChange={e => this.changeProductNumber(product.id, e)}
                  type="number"
                />
                <button
                  className="btn btn-danger"
                  type="button"
                  onClick={() => deleteCarts(product.id)}
                >
                  删除
                </button>
              </div>
            </div>
          ))}
        </div>
        <div className="cart-total">
          <strong className="cart-total-title">总价</strong>
          <span className="cart-total-price">￥{
            carts.reduce((total, product) => {
              return total += product.price * product.count
            }, 0)
          }</span>
        </div>
      </section>
    )
  }
}

const mapStateToProps = state => ({
  carts: state.carts.carts
})

const mapDispatchToProps = dispatch => ({
  ...bindActionCreators(cartAction, dispatch)
})

export default connect(mapStateToProps, mapDispatchToProps)(Cart)
